package com.woniuxy.controller;

import com.woniuxy.pojo.Menu;
import com.woniuxy.pojo.PageBean;
import com.woniuxy.pojo.Role;
import com.woniuxy.service.MenuService;
import com.woniuxy.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    @RequestMapping("goList.html")
    public String goUserList(@RequestParam(name = "currentPage",defaultValue = "1") Integer currentPage,
                             @RequestParam(defaultValue = "2") Integer pageSize,
                             Role quertRole,
                             HttpServletRequest request){
        PageBean pageBean = new PageBean();
        pageBean.setQueryObj(quertRole);
        //通过查询条件查询总条目
        Integer totalSize = roleService.getTotalSize(pageBean);
        //通过总条目和每页条目计算总页数
        Integer pages = roleService.getPages(totalSize, pageSize);
        pageBean.setPages(pages);
        //判断当前页是否超范围
        if (currentPage > pages){
            currentPage = pages;
        }
        if (currentPage<1){
            currentPage=1;
        }
        //设置pageBean属性
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        Integer start = (pageBean.getCurrentPage()-1)*(pageBean.getPageSize());
        pageBean.setStart(start);
        //根据分页和查询条件查询数据
        List<Role> roleList = roleService.getRoleListByPage(pageBean);
        pageBean.setData(roleList);
        pageBean.setTotalSize(totalSize);
        System.out.println(pageBean.getData());
        request.setAttribute("pageBean",pageBean);
        return "role_goList";
    }
    @RequestMapping("goAssign.html")
    public String goAssign(Integer roleId,HttpServletRequest request){
        request.setAttribute("roleId",roleId);
        return "role_assign";
    }
    @RequestMapping("getCheck.html")
    @ResponseBody
    public Integer[] checkMenu(Integer roleId){
        return roleService.getMenuIdsByRoleId(roleId);
    }
    @RequestMapping("assignPerm.html")
    @ResponseBody
    public Boolean assignPerm(String menuIds , Integer roleId){
        Boolean flag = this.menuService.assignPermission(roleId, menuIds);
        return flag;
    }
}
